<script lang='ts' setup>
import { reactive, ref } from 'vue';
import { AxiosResponse } from 'axios'
import { orgUnitTree, OrgUnitTreeNode } from '/@/api/org/tree'
import { ReturnTree } from '/@/_types/api/return-type'

//共三个参数，依次为：传递给 data 属性的数组中该节点所对应的对象、节点对应的 Node、节点组件本身。
const emit = defineEmits<{
    (e: 'node-click', row: ReturnTree<any>, column: any, event: Event): void//行点击事件
}>()

const props = defineProps({
    showCheckbox: {
        type: Boolean,
        default: false
    }
})

const elTreeRef = ref();

const UnitAsyncTreeState = reactive({
    props: {
        label: 'text',
        children: 'children',
        isLeaf: 'leaf'
    },
    /**过滤树数据 */
    filterTreeData: (treeData: ReturnTree<OrgUnitTreeNode>[]) => {
        const treeNodeArr: any[] = []
        treeData.forEach(item => {
            let treeNode: any = item
            treeNode.leaf = !item.isParent
            treeNodeArr.push(treeNode)
        })
        return treeNodeArr
    },
    /**异步树加载 */
    loadNode: (node: any, resolve: any) => {
        let queryparam: any = {}
        queryparam.id = node.level === 0 ? '0' : node.data.id
        orgUnitTree(queryparam).then((res: AxiosResponse<ReturnTree<any>[]>) => {
            resolve(UnitAsyncTreeState.filterTreeData(res.data))
        }).finally(() => {
            //loadingInstance?.close()
        })
    },
    /**节点点击事件 */
    handleNodeClick: (treeData: ReturnTree<any>, column: any, event: Event) => {
        emit("node-click", treeData, column, event)
    },
})

defineExpose({
    getSelectedData: () => {
        return elTreeRef.value.getCurrentNode()
    },
    getCheckedNodes: () => {
        return elTreeRef.value.getCheckedNodes()
    }
})

</script>
<template>
    <el-tree
        ref="elTreeRef"
        highlight-current
        lazy
        :show-checkbox="showCheckbox"
        node-key="id"
        :props="UnitAsyncTreeState.props"
        :load="UnitAsyncTreeState.loadNode"
        :default-expanded-keys="['10000']"
        @node-click="UnitAsyncTreeState.handleNodeClick"
    />
</template>